package Game;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {
	
	private static GUI gui;
	private static Connection connection;
	private static Game game;
	
	protected static void mainInit() {
		gui = new GUI();
	}
	
	protected static void mainFinal() {
		if (connection != null) {
			connection.close();
		}
	}
	
	protected static boolean createServer(int port) {
		// TODO wait for connection;
		return connection.serverErstellen(port);
	}
	
	protected static boolean connectToServer(String ip, int port) {
		// TODO create connection;
		connection = new Connection(ip, port);
		return connection.isRunning();
}

	protected static void connectionLost() {
		gui.connectionLost();
	}
	
	protected static void newGame(Player.PlayerID id) {
		if (connection != null && connection.newGame(id)) {
			game = new Game(id);
			gui.newGame();
		}
	}
	
	protected static boolean click(Player.PlayerID id, int x, int y) {
		if (game != null && game.updateField(id, x, y)) {
			gui.updateField(x, y);
			connection.updateField(id, x, y);
			return true;
		} else {
			return false;
		}
	}
	
	protected static boolean click(Player.PlayerID id, int x, int y, int xx, int yy) {
		return click(id, 3 * x + xx, 3 * y + yy);
	}
	
	protected static Game.FieldState getFieldState(int x, int y) {
		if (game != null) {
			return game.getFieldState(x, y);
		} else {
			return null;
		}
	}
	
	protected static Player.PlayerID getPlayer(int x, int y) {
		if (game != null) {
			return game.getPlayer(x, y);
		} else {
			return null;
		}
	}
	
	protected static Player.PlayerID getPlayer(int x, int y, int xx, int yy) {
		return getPlayer(3 * x + xx, 3 * y + yy);
	}
	
	protected static void sendMessage(String message) {
		message = StringFilter.filterString(message);
		if (message != null) {
			receiveMessage(Strings.getString("you") + ": " + message);
			if (connection != null) {
				connection.sendMessage(Player.getPlayerByID(Player.PlayerID.you).getName() + ": " + message);
			}
		}
	}
	
	protected static void receiveMessage(String message) {
		gui.addLine(message);
	}
	
	private Main() {};

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Main.mainInit();
	}

}
